var list = new ArrayList();
var  proxyTime=0;

load("js/luaclient.js")

var v4_citic_credit_java_funcs = {

    openHomePage : function(){
        logger.info("CITCICREDIT taskkey={} 检查当前代理是否可用 {}",context.get(LUA_TASK_KEY),context.get(LUA_TASK_PROXY_INFO));
        var	html = get("https://creditcard.ecitic.com/citiccard/ucweb/entry.do");
        storeDataToFile(context,html, "loginHtml.html");
    },

    checkControlAvailable:function(){ return true },
    checkTargetWebsiteAvailable: function(){ return true },
    //检查代理是否可用
    checkProxyAvailable: function () {


        var isCorrectFunc = function(){
            return is_exist_by_id("phoneNbr")
        }
        var getErrorMsgFunc = function() {
            return "代理ip异常";
        }
        return assertTrueOrThrowException("", isCorrectFunc, getErrorMsgFunc)

    },
    needRefreshHomePageOrNot : function() {
        return equals(context.get("currentErrorCode"), BALO_99602_50)
    },
    needResetEnvironment:function(){
        return equals(context.get("currentErrorCode"),BALO_99602_40);
    },
    login:function () {
        var mobile = getLoginParams(context)[0];
        set_input_text_by_id("phoneNbr", mobile);
        var code=inputImg();
        inputSms(mobile,code);
        //当前链接
        var sms_currentUrl=get_url();
        logger.info("sms_currentUrl="+sms_currentUrl);
        //https://creditcard.ecitic.com/citiccard/ucweb/toSetMm.do 注册链接
        if(sms_currentUrl.contains("toSetMm.do")){
            throwBankExceptionByErrorMsg("您还未绑卡，暂不支持业务办理");
        }
        //https://creditcard.ecitic.com/citiccard/ucweb/entry.do  首页
        //点击下一步,仍然停留在首页,说明当前流程中断,返回错误信息
        if(sms_currentUrl.contains("entry.do")){
            var screenShots = luaFuncs.getScreenShots();
            logger.info("下一步截图路径{}", screenShots);
            //点击下一步页面,出现错误
            var nextErrorMsg=luaFuncs.getInnerHTML("reg_phone_error");
            //有错误信息，才会包含<i></i>，没有错误信息，由于网络原因，可能返回return is null
            if(nextErrorMsg.contains("<i></i>")) {
                throwBankExceptionByErrorMsg(nextErrorMsg.replace("<i></i>", ""));
            }
        }
        Thread.sleep(500);
        var pWord = context.get(Constants.LUA_TASK_TOKEN);
        var inputPassWordByIdResult=inputPassWordById(pWord);
        logger.info("presult="+inputPassWordByIdResult);
        clickLoginButton("login");
        var login_currentUrl=get_url();
        logger.info("login_currentUrl_1="+login_currentUrl);
        //https://creditcard.ecitic.com/citiccard/ucweb/memberset.do 重置
        //登录信息校验
        var loginMsg=luaFuncs.getInnerHTML("mm_emsg");
        logger.info("loginMsg="+loginMsg);
        var screenShots = luaFuncs.getScreenShots();
        logger.info("登录截图路径{}", screenShots);
        //登录时返回的错误信息
        if(loginMsg!=""){
            if(loginMsg.contains("<i></i>")){
                throwBankExceptionByErrorMsg(loginMsg.replace("<i></i>",""));
            }
        }
        // 获取首页源码 判断是否进入主页
        var indexPage = luaFuncs.zx_get_html();
        storeDataToFile(context,indexPage, "indexPage.html");
        var postdatam = new HashMap();
        //获取卡列表页面
        var cardHtmlm = ajax_post("https://creditcard.ecitic.com/citiccard/newonline/common.do?func=querySignCards", postdatam);
        Thread.sleep(200);
        storeDataToFile(context,cardHtmlm, "cardList.html");
        var smsCheckResult = {};
        if (cardHtmlm.indexOf("您还未绑卡")!=-1 || !(cardHtmlm.indexOf("cardlist")!=-1)) {
            smsCheckResult.errorMsg = "您还未绑卡，暂不支持业务办理"
            smsCheckResult.statuts = "EMPTYCARD";
        }else{
            context.put("cardHtmlm", cardHtmlm) ;
            context.put("indexPage", indexPage) ;
            smsCheckResult.statuts = "OK";
        }
        var checkCardListFunc = function (smsCheckResult) {
            return equals(smsCheckResult.statuts, "OK");
        }
        var getCheckCardListError = function (smsCheckResult) {
            return smsCheckResult.errorMsg;
        }
        return assertTrueOrThrowException(smsCheckResult, checkCardListFunc, getCheckCardListError)
    },
    //抓取过程
    crawl :function(){
        var taskKey = context.get(LUA_TASK_KEY) ;
        var cardHtmlm = context.get("cardHtmlm") ;
        var indexPage = context.get("indexPage") ;
        var doc = Jsoup.parse(cardHtmlm);
        var cardlist = doc.select("cardlist");
        for (var j = 0; j < cardlist.size(); j++) {
            var fullCard = cardlist.get(j).attr("card_nbr_no");
            var card_num = fullCard.substring(fullCard.length() - 4,
                fullCard.length());
            // 默认第一张卡
            var card_no = cardlist.get(j)
                .attr("card_nbr");
            var crytype = cardlist.get(j)
                .attr("crytype1");
            // 声明存储对象
            var creditCardAllData = new CreditCardAllData();
            // 声明存储金额列表
            var deposits = new ArrayList();
            // 声明账单列表
            var bills = new ArrayList();
            creditCardAllData.setBills(bills);
            creditCardAllData.setDeposits(deposits);

            try {
                //在首页获取卡主姓名
                getIndexPageParse(indexPage, creditCardAllData);
            } catch ( e) {
                statCaughtException(context, e);
                logger.info("解析首页信息数据异常",e);
            }
            var postdata = new HashMap ();
            //获取两个含有基本信息的页面
            var userHtml = ajax_post("https://creditcard.ecitic.com/citiccard/newonline/settingManage.do?func=queryUserInfo", postdata);
            storeDataToFile(context,userHtml, j+"_user_1.html");
            if (userHtml.indexOf("代理服务器没有响应")!==-1) {
                logger.info("任务" + taskKey + "个人信息：代理服务器没有响应");
                return;
            }
            var postdatac = new HashMap ();
            var cardHtml = ajax_post("https://creditcard.ecitic.com/citiccard/newonline/common.do?func=querySignCards",
                postdatac);
            storeDataToFile(context,cardHtml, j+"_card_1.html");
            if (cardHtml.indexOf("代理服务器没有响应")!==-1) {
                logger.info("任务" + taskKey + "卡号信息：代理服务器没有响应");
                return;
            }
            try {
                getBasicNeedInfo(userHtml, cardHtml, creditCardAllData,
                    card_num);
            } catch (e) {
                statCaughtException(context, e);
                logger.info("解析基本信息数据异常",e);
            }
            var postdatal = new HashMap ();
            postdatal.put("cardNo", card_no);
            postdatal.put("count", "12");
            postdatal.put("crytype", crytype);
            postdatal.put("rowsPage", "10");
            postdatal.put("start_pos", "1");
            postdatal.put("startpos", "1");
            postdatal.put("stmt_date", "");
            //获取已出账单页面
            var billHtml = ajax_post("https://creditcard.ecitic.com/citiccard/newonline/billQuery.do?func=queryBillInfo", postdatal);
            storeDataToFile(context,billHtml, j+"_bill_1.html");
            if (billHtml.indexOf("代理服务器没有响应")!==-1) {
                logger.info("任务" + taskKey + "账号信息：代理服务器没有响应");
                return;
            }
            try {
                parseBillInfo(billHtml, bills,card_no,crytype,j);
            } catch ( e) {
                statCaughtException(context, e);
                logger.info("解析账单数据异常",e);
            }


            var postdatau = new HashMap();
            postdatau.put("cardNo", card_no);
            postdatau.put("crytype", crytype);
            postdatau.put("rowsPage", "10");
            postdatau.put("startpos", "1");
            postdatau.put("stmt_date", "");
            //获取未出账单页面
            var unbilldetailHtml = ajax_post("https://creditcard.ecitic.com/citiccard/newonline/billQuery.do?func=queryUnSettleBill", postdatau);
            storeDataToFile(context,unbilldetailHtml, j+"_undonepage_1.html");

            unbilldetailHtml=checkCurrentNetBusy(unbilldetailHtml,postdatau,"https://creditcard.ecitic.com/citiccard/newonline/billQuery.do?func=queryUnSettleBill")
            storeDataToFile(context,unbilldetailHtml, j+"_undonepage_2.html");

            if (unbilldetailHtml.indexOf("代理服务器没有响应")!==-1) {
                logger.info("任务" + taskKey + "账号信息：代理服务器没有响应");
                return;
            }
            try {
                parseUnbillDetailInfo(unbilldetailHtml, bills);
            } catch ( e) {
                statCaughtException(context, e);
                logger.info("解析未出账单数据异常",e);
            }
            list.add(creditCardAllData);
        }

        context.put("credit_data", list) ;
    },
    exitLogin :function () {
    }
}
var index = 0;
function inputImg(mobile) {
    index ++;
    var  code="";
    //检验是否需要输入验证码
    var flag = luaFuncs.zx_check_img();
    if (StringUtils.equals(flag, "true")) {
        var img = get_image_by_id("randImage");
        var checkImgExisted = function (img) {
            if(img.contains("fail")){
                return false
            }
            return true;
        }
        var getErrorMsg = function () {
            if (index >3){
                return "处理数据失败，请稍后再试";
            }
            return "图形验证码输入错误，请重新输入"
        }
        assertTrueOrThrowException(img, checkImgExisted, getErrorMsg);
        var taskKey =context.get(LUA_TASK_KEY) ;
        context.put(TASK_IMG_PATH, img) ;
        context.put(TASK_IMG_REGEX,"[0-9a-zA-Z]{4}");
        //获取验证码
        code = waitImgCodeBySecondsByJs(context,120,true,3);
        logger.info("code_0="+code);
        if (StringUtils.isBlank(code) || code.length() < 4) {
            logger.info("任务" + taskKey
                + "验证码信息：打码位数不足四位，手动补足 {}", code);
            code = "1234";
        }
        //输入验证码
        set_input_text_by_id("imgvalicode", code);// 输入验证码
        Thread.sleep(1000);
    }
    return code;
}


function inputSms(mobile,code) {
    // var paramMap=new HashMap();
    // var timestamp= new Date().getTime();
    // paramMap.put("phone",mobile);
    // if(StringUtils.isNotBlank(code)){
    //     paramMap.put("imgValidCode",code);
    // }
    // var result=ajax_post("https://creditcard.ecitic.com/citiccard/ucweb/getsms.do?timestamp"+timestamp, paramMap);
    // Thread.sleep(500);
    // logger.info("result="+result);
    // var resultJson="";
    // try {
    //     resultJson = JSON.parse(result);
    // } catch (e) {
    //     logger.info("网络原因未获取到结果,再次尝试请求");
    //     var result=ajax_post("https://creditcard.ecitic.com/citiccard/ucweb/getsms.do?timestamp"+timestamp, paramMap);
    //     logger.info("result_repeat="+result)
    //     Thread.sleep(500);
    //     resultJson = JSON.parse(result);
    // }
    // //非正确状态
    // if(!"0000000".equals(resultJson.get("resultCode"))){
    //     var errorMsg=resultJson.get("resultDesc");
    //     throwBankExceptionByErrorMsg(errorMsg);
    // }

   // set_input_text_by_id("imgValidCode",code);
    //点击"免费获取"按钮 getsms
    clickNextById("getsms");
    //点击下一步页面,出现错误
    var imgMsg=luaFuncs.getInnerHTML("reg_phone_error");
    //有错误信息，才会包含<i></i>，没有错误信息，由于网络原因，可能返回return is null
    logger.info("imgMsg="+imgMsg);
    if(imgMsg.contains("<i></i>")) {
        var screenShots = luaFuncs.getScreenShots();
        logger.info("点击免费获取截图路径{}", screenShots);
        var errorMsg=imgMsg;
        //清空内容
        luaFuncs.clearInnerHTML("reg_phone_error");
        throwBankExceptionByErrorMsg(errorMsg.replace("<i></i>", ""));
    }
     var sms = waitSmsCodeBySeconds(context,120);
    //输入短信验证码
    var status=set_input_text_by_id("valicode", sms);
    logger.info("valicode_status="+status);
    Thread.sleep(800);
    //点击
    clickNextById("checkcode");
    Thread.sleep(200);
}
//点击下一步
function clickNextById(id) {
    var map = new LinkedHashMap();
    map.put("method", "clickNextById");
    map.put("id",id);
    return sendAndReceive(map);
}

//输入密码
function inputPassWordById(pWord){
    var map = new LinkedHashMap();
    map.put("method", "inputPassWordById");
    map.put("pWord",pWord);
    return sendAndReceive(map);
}

//点击登录
function clickLoginButton(id){
    var map = new LinkedHashMap();
    map.put("method", "clickLoginButton");
    map.put("id",id);
    return sendAndReceive(map);
}

/**
 * 判断当前请求是否为网络繁忙
 * @param currenthtml
 * @param postdatas
 * @param url
 * @returns {*}
 */
function checkCurrentNetBusy(currenthtml,postdatas,url){
    logger.info("中信  taskKey = {} 检查当前请求返回的结果是否为网络繁忙",context.get(LUA_TASK_KEY));
    for(var index=0;index<3;index++) {
        if(currenthtml.indexOf("网络繁忙!请稍后再试")!==-1){
            logger.info("中信  taskKey = {} 检查当前请求返回的结果为网络繁忙!!!!!!!!!!等待再次第{}请求",context.get(LUA_TASK_KEY),(index+1));
            Thread.sleep(3000*index)
            currenthtml=ajax_post(url, postdatas);
        }else if(currenthtml==null||currenthtml==""){
            logger.info("未抓取到有效数据")
            Thread.sleep(500*index);
            currenthtml=ajax_post(url, postdatas);
        } else{
            return currenthtml;
        }
    }

    return currenthtml;
}



/**
 * @throws InterruptedException
 *
 */
function checkSmsHtmlComplete() {
    var index=1;
    while(index<4){
        var dynamicSmsHtml = luaFuncs.get_html_2();
        var is_exister_by_id_flag=is_exist_by_id("dtsecretcode");
        if (is_exister_by_id_flag) {
            return;
        }
        logger.info("中信 taskKey={}第{}次 循环等待页面加载完成！",context.get(LUA_TASK_KEY),index);
        if (!is_exister_by_id_flag && dynamicSmsHtml.contains("验证手机短信验证码-中信银行信用卡中心")) {
            Thread.sleep(5000);
        }
        index++;
    }
}


// 判断是否全部数字
function isAllNum(str) {
    if (StringUtils.isEmpty(str))
        return false;
    var regex = "^\\d+$";
    var pattern = Pattern.compile(regex);
    var matcher = pattern.matcher(str);
    return matcher.matches();
}


/**
 * 判断当前字符串是或否为
 * @param str
 * @return
 */
function isIdCard18( str){
    if (StringUtils.isEmpty(str))
        return false;
    var regex = "(^\\d{18}$)|(^\\d{17}[Xx]$)";
    var pattern = Pattern.compile(regex);
    var matcher = pattern.matcher(str);
    var flag = false;
    if (matcher.matches()) {
        var oVerifyBit = str.substring(17);
        var nVerifyBit = getVerifyBit(str.substring(0, 17));
        var cal = Calendar.getInstance();
        var sysYear = cal.get(Calendar.YEAR);
        var year = Integer.parseInt(str.substring(6, 10));
        var month = Integer.parseInt(str.substring(10, 12));
        var day = Integer.parseInt(str.substring(12, 14));
        if (year >= (sysYear - INTERVAL) && year <= sysYear && month > 0 && month < 13 && day > 0 && day < 32
            && StringUtils.equalsIgnoreCase(oVerifyBit, nVerifyBit)) {
            flag = true;
        }
    }
    return flag;
}

var WI = new Array ( 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
var VI = new Array( "1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2" );
var INTERVAL = 120;
function getVerifyBit( str) {
    if (StringUtils.isBlank(str) || str.length() != 17)
        return null;
    var ai = new Array([str.length()]);
    for (var i = 0; i < str.length(); i++) {
        ai[i] = Integer.parseInt(str.substring(i, i + 1));
    }
    var num = 0;
    for (var i = 0; i < 17; i++) {
        num += ai[i] * WI[i];
    }
    var remaining = num % 11;
    return VI[remaining];
}


// 判断是否全部数字
function isAllNum(str) {
    if (StringUtils.isEmpty(str))
        return false;
    var regex = "^\\d+$";
    var pattern = Pattern.compile(regex);
    var matcher = pattern.matcher(str);
    return matcher.matches();
}


function getIndexPageParse( indexPage, creditCardAllData) {
    var doc = Jsoup.parse(indexPage);
    var tiles = doc.select("p").select("[class='title']").text()
        .split("，");
    var name_on_card = tiles[1].trim();
    creditCardAllData.setNameOnCard(name_on_card);
}

function parseUnbillDetailInfo( unbilldetailHtml,  bills){
    var doc = Jsoup.parse(unbilldetailHtml);
    var head = RegexUtils.GetText(unbilldetailHtml, "<head.*?/>");
    var bill_date = RegexUtils.GetText(head, "\\d{4}-\\d{2}-\\d{2}");

    var billAllData = new BillAllData();
    billAllData.setBillType("UNDONE");
    var sdf = new SimpleDateFormat("yyyy-MM-dd");
    var date = sdf.parse(bill_date);
    var rightNow = Calendar.getInstance();
    rightNow.setTime(date);
    rightNow.add(Calendar.MONTH, 1);// 日期加1月
    var dt1 = rightNow.getTime();
    var reStr = sdf.format(dt1);
    if(StringUtils.equals("0000-00-00", bill_date)){
        var calendar =Calendar.getInstance();
        var year = calendar.get(Calendar.YEAR);
        var month=calendar.get(calendar.MONTH)+1;
        var monthInt=Integer.parseInt(month);
        if(monthInt<10){
            month="0"+month;
        }
        reStr = year + "-" + month + "-01";
    }
    var bill_id = UUID.randomUUID().toString() ;
    billAllData.setBillId(bill_id);
    billAllData.setBankName("中信银行");
    billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(reStr));
    billAllData.setBillMonth(reStr.substring(0, 7));
    billAllData.setCreditLimit(null);
    billAllData.setCashLimit(null);
    billAllData.setUsdCashLimit(null);
    billAllData.setUsdCreditLimit(null);
    billAllData.setUsdInterest(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setUsdNewCharges(null);
    billAllData.setUsdNewBalance(null);
    var new_charge = new BigDecimal("0") ;//未出账单新增账金额
    var new_balance = new BigDecimal("0") ;//未出账单
    var shopps = doc.select("billDetailList");
    var shopps1 = doc.select("billDetailList");//用于分期解析
    var shopping_sheets = new ArrayList();// 消费记录
    var installments = new ArrayList();//分期记录
    var j = 1;
    for(var i=0;i<shopps.size();i++){
        var shopp = shopps.get(i);
        // for (Element shopp : shopps) {
        var expense = new Expense();
        var shoppingsheet_id = UUID.randomUUID().toString() ;
        expense.setId(shoppingsheet_id);
        var remark = shopp.attr("tran_code");
        var amount_money = shopp.attr("tran_amt").replaceAll(",", "");
        var trans_date = shopp.attr("tran_date");
        var post_date = shopp.attr("post_date");
        var tran_desc = shopp.attr("tran_desc");
        var card_4_num = shopp.attr("card_4_num");

        expense.setBalance(null);
        expense.setCardNum(card_4_num);
        expense.setDescription(tran_desc.replace(" ", ""));
        expense.setAmountMoney(new BigDecimal(amount_money));
        expense.setRemark(remark);
        expense.setCategory(CreditResultUtil.judgeBillCategorys(tran_desc,
            expense.getAmountMoney()));
        if(tran_desc.indexOf("期")!==-1&&tran_desc.indexOf("手续费")!==-1){
            expense.setCategory("INSTALLMENT");
        }
        if(!tran_desc.indexOf("还款")!==-1 && !remark.indexOf("还款")!==-1){
            new_charge = new_charge.add(new BigDecimal(amount_money)) ;
        }
        new_balance = new_balance.add(new BigDecimal(amount_money)) ;
        expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date+" 00:00:00"));
        expense.setPostDate(yyyy_MM_dd_PARSER.parse(post_date));
        expense.setTransAddr("");
        expense.setTransMethod("");
        expense.setTransChannel("");
        expense.setOrderIndex(j++);
        expense.setCurrencyType("CNY");
        expense.setOppositeBank("");
        expense.setOppositeCardNo("");
        expense.setNameOnOppositeCard("");
        var lists =getMatch("\\s*(\\d{1,3}/\\d{1,3})", tran_desc) ;
        if (lists.size() == 1 && !tran_desc.indexOf("手续费")!==-1) {
            var installment = new Installment();
            var terms = lists.get(0);
            var termsArr = terms.get(0).split("/");
            if (termsArr.length == 2) {
                var dqTerm = Integer.parseInt(termsArr[0]);
                var totalTerm = Integer.parseInt(termsArr[1]);
                installment.setCurrencyType("CNY");
                installment.setCurrentMonth(dqTerm);
                var installment_type = "CONSUME";
                if (tran_desc.indexOf("账单")!==-1) {
                    installment_type = "BILL";
                } else if (tran_desc.indexOf("现金")!==-1 || tran_desc.indexOf("圆梦金")!==-1) {
                    installment_type = "CASH";
                }
                installment.setInstallmentType(installment_type);
                installment.setPostDate(yyyy_MM_dd_PARSER.parse(post_date));
                installment.setShoppingsheetId(shoppingsheet_id);
                installment.setTotalMonth(totalTerm);
                if(trans_date!=null){
                    trans_date=trans_date+" 00:00:00";
                }

                installment.setTransDate(yyyy_MM_dd_PARSER.parse(trans_date));
                installment.setAmountMoney(new BigDecimal(amount_money));
                installment.setInstallmentDesc(tran_desc.replace(" ", ""));
                installment.setTransferFee(null);
                for (var k = 0; k < shopps1.size(); k++) {
                    var shopp1 = shopps1.get(k);
                    var description1 = shopp1.attr("tran_desc");
                    var amount_money1 = shopp1.attr("tran_amt").replaceAll(",", "");
                    if (description1.indexOf("手续费")!==-1) {
                        installment.setHandingFee(new BigDecimal(amount_money1));
                        installment.setHandingfeeDesc(description1.replace(" ", ""));
                        shopps1.remove(k);
                        break ;
                    }
                }
                expense.setCategory("INSTALLMENT") ;
            }
            installments.add(installment);
        }
        shopping_sheets.add(expense);
    }
    billAllData.setNewCharges(new_charge);
    billAllData.setShoppingSheets(shopping_sheets);
    billAllData.setInstallments(installments);
    billAllData.setInterest(null);
    billAllData.setMinPayment(null);
    billAllData.setLastPayment(null);
    try {
        var last_balance = context.get("new_balance") ;
        billAllData.setLastBalance(StringUtils.isEmpty(last_balance)?null:new BigDecimal(last_balance));
        billAllData.setNewBalance(StringUtils.isEmpty(last_balance)?new_balance:new BigDecimal(last_balance).add(new_balance));
    } catch ( e) {
        statCaughtException(context, e);
        logger.error("计算本期账单金额计算错误",e);
    }
    bills.add(billAllData);
}

function parseBillDetailInfo(billdetailHtml,  bills) {
    var doc = Jsoup.parse(billdetailHtml);
    var bill_monthss = doc.select("billProfile").first();
    if(bill_monthss==null) {
        logger.info("中信  taskKey = {} 获取到的账单月为null,停止解析该月，继续抓取下一个月",context.get(LUA_TASK_KEY) )
        return
    }
    var bill_month = doc.select("billProfile").first().attr("bills_month");
    var bill_date = doc.select("billProfile").first().attr("stmt_date");
    var payment_due_date = doc.select("billProfile").first()
        .attr("dte_pymt_due");
    var new_balance = doc.select("billProfile").first().attr("cur_amt").replaceAll(",", "");
    var min_payment = doc.select("billProfile").first().attr("min_pay").replaceAll(",", "");
    var last_balance = doc.select("billProfile").first().attr("pre_pay").replaceAll(",", "");
    var last_payment = doc.select("billProfile").first().attr("pre_hpay").replaceAll(",", "");
    var new_charges = doc.select("billProfile").first().attr("bq_xz").replaceAll(",", "");
    // var interest = doc.select("billProfile").first().attr("bq_shou_fei").replaceAll(",", "");
    var billAllData = new BillAllData();
    var bill_id = UUID.randomUUID().toString() ;
    billAllData.setBillId(bill_id);
    billAllData.setBillType("DONE");
    billAllData.setBankName("中信银行");
    var stringBuffer = new StringBuffer(bill_month);
    bill_month = stringBuffer.insert(4, "-").toString();
    billAllData.setBillMonth(bill_month);
    var stringBuffers = new StringBuffer(bill_date);
    bill_date = stringBuffers.insert(4, "-").insert(7, "-").toString();
    billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(bill_date));
    payment_due_date = payment_due_date.replaceAll("年", "-")
        .replaceAll("月", "-").replaceAll("日", "");
    if(payment_due_date!==null&&payment_due_date.length!==0){
        billAllData.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(payment_due_date));
    }
    billAllData.setInterest(null);
    billAllData.setNewBalance(new BigDecimal(new_balance));
    billAllData.setMinPayment(new BigDecimal(min_payment));
    billAllData.setLastBalance(new BigDecimal(last_balance));
    billAllData.setLastPayment(new BigDecimal(last_payment).negate());
    billAllData.setNewCharges(new BigDecimal(new_charges));
    billAllData.setCreditLimit(null);
    billAllData.setCashLimit(null);
    billAllData.setUsdCashLimit(null);
    billAllData.setUsdCreditLimit(null);
    billAllData.setUsdInterest(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setUsdNewCharges(null);
    billAllData.setUsdNewBalance(null);

    var shopps = doc.select("billDetailList");
    var shopps1 = doc.select("billDetailList");//用于分期解析
    var shopping_sheets = new ArrayList();// 消费记录
    var installments = new ArrayList();//分期记录
    var j = 1;
    for(var i=0;i<shopps.size();i++){
        var shopp = shopps.get(i);
        // for (Element shopp : shopps) {
        var expense = new Expense();
        var shoppingsheet_id = UUID.randomUUID().toString() ;
        expense.setId(shoppingsheet_id);
        var description = shopp.attr("tran_desc");
        var remark = shopp.attr("tram_code");
        var amount_money = shopp.attr("tran_amt").replaceAll(",", "");;
        var trans_date = shopp.attr("tran_date");
        var post_date = shopp.attr("post_date");
        var card_4_num = shopp.attr("card_4_num");
        //填充数据
        expense.setBalance(null);
        expense.setRemark(remark);
        expense.setDescription(description.replace(" ", ""));
        expense.setAmountMoney(new BigDecimal(amount_money));
        expense.setCategory(CreditResultUtil.judgeBillCategorys(description, expense.getAmountMoney()));
        if(description.indexOf("期") !==-1 &&description.indexOf("手续费")!==-1){
            expense.setCategory("INSTALLMENT");
        }
        expense.setCardNum(card_4_num);
        expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date+" 00:00:00"));
        expense.setTransAddr("");
        expense.setTransMethod("");
        expense.setTransChannel("");
        expense.setOrderIndex(j++);
        expense.setCurrencyType("CNY");
        expense.setOppositeBank("");
        expense.setOppositeCardNo("");
        expense.setNameOnOppositeCard("");
        expense.setPostDate(yyyy_MM_dd_PARSER.parse(post_date));
        var lists =getMatch("\\s*(\\d{1,3}/\\d{1,3})", description) ;
        //根据正则表达式来判断是否为分期数据
        if (lists.size() == 1 && !description.contains("手续费")) {
            var installment = new Installment();
            var terms = lists.get(0);
            var termsArr = terms.get(0).split("/");
            if (termsArr.length == 2) {
                var dqTerm = Integer.parseInt(termsArr[0]);
                var totalTerm = Integer.parseInt(termsArr[1]);
                installment.setCurrencyType("CNY");
                installment.setCurrentMonth(dqTerm);
                var installment_type = "CONSUME";
                if (description.indexOf("账单")!==-1) {
                    installment_type = "BILL";
                } else if (description.indexOf("现金")!==-1 || description.indexOf("圆梦金")!==-1) {
                    installment_type = "CASH";
                }
                installment.setInstallmentType(installment_type);
                installment.setPostDate(yyyy_MM_dd_PARSER.parse(post_date));
                installment.setShoppingsheetId(shoppingsheet_id);
                installment.setTotalMonth(totalTerm);
                if(trans_date!=null){
                    trans_date=trans_date+" 00:00:00";
                }
                installment.setTransDate(yyyy_MM_dd_PARSER.parse(trans_date));
                installment.setAmountMoney(new BigDecimal(amount_money));
                installment.setInstallmentDesc(description.replace(" ", ""));
                installment.setTransferFee(null);
                for (var k = 0; k < shopps1.size(); k++) {
                    var shopp1 = shopps1.get(k);
                    var description1 = shopp1.attr("tran_desc");
                    var amount_money1 = shopp1.attr("tran_amt").replaceAll(",", "");
                    if (description1.indexOf("手续费")!==-1) {
                        installment.setHandingFee(new BigDecimal(amount_money1));
                        installment.setHandingfeeDesc(description1.replace(" ", ""));
                        shopps1.remove(k);
                        break ;
                    }
                }
                expense.setCategory("INSTALLMENT") ;
            }
            installments.add(installment);
        }
        shopping_sheets.add(expense);
    }
    billAllData.setShoppingSheets(shopping_sheets);
    billAllData.setInstallments(installments);
    bills.add(billAllData);
    if(StringUtils.isEmpty(context.get("new_balance"))){
        context.put("new_balance", new_balance) ;//
    }
}

/**
 * 解析基本信息页面 填充数据
 * @param userHtml
 * @param cardHtml
 * @param creditCardAllData
 * @param card_num
 */
function getBasicNeedInfo(userHtml,  cardHtml,  creditCardAllData,  card_num) {
    var doc = Jsoup.parse(cardHtml);
    var cardlist = doc.select("cardlist");
    for (var i = 0; i < cardlist.size(); i++) {
        var fullCardNum = cardlist.get(i).attr("card_nbr_no");
        if (fullCardNum.endsWith(card_num)) {
            var balance = cardlist.get(i).attr("avail_credit_b");
            var cash_balance = cardlist.get(i).attr("avail_cash_b");
            creditCardAllData.setBalance(new BigDecimal(balance.replaceAll(",", "")));
            creditCardAllData.setFullCardNum(fullCardNum);
            creditCardAllData.setBankName("中信银行");
            creditCardAllData.setCardId(UUID.randomUUID().toString());
            creditCardAllData.setCardNum(fullCardNum.substring(fullCardNum.length() - 4, (fullCardNum.length())));
            creditCardAllData.setCardType("信用卡");
            creditCardAllData.setCashBalance(new BigDecimal(cash_balance.replaceAll(
                ",", "")));
            creditCardAllData.setCreditLimit(null);
            creditCardAllData.setCashLimit(null);
        }
    }
}
/**
 * 解析已出账单页面
 * @param billHtml
 * @param bills
 * @param card_no
 * @param crytype
 * @param j
 */
function parseBillInfo(billHtml, bills,  card_no,  crytype,  j) {
    var billsList = Jsoup.parse(billHtml).select("billsMonthList");
    for(var i=0;i<billsList.size();i++){
        Thread.sleep(1500)
        var billinfo = billsList.get(i);
        var bills_month = billinfo.attr("stmt_date");
        var postdatas = new HashMap();
        postdatas.put("cardNo", card_no);
        postdatas.put("count", "12");
        postdatas.put("crytype", crytype);
        postdatas.put("rowsPage", "10");
        postdatas.put("start_pos", "1");
        postdatas.put("startpos", "1");
        postdatas.put("stmt_date", bills_month);
        logger.info("postdatas=\n"+postdatas.toString());
        var billdetailHtml =ajax_post("https://creditcard.ecitic.com/citiccard/newonline/billQuery.do?func=queryBillInfo", postdatas);
        Thread.sleep(500);
        if(billdetailHtml==null){
            Thread.sleep(500);
            billdetailHtml =ajax_post("https://creditcard.ecitic.com/citiccard/newonline/billQuery.do?func=queryBillInfo", postdatas);

        }
        storeDataToFile(context,billdetailHtml, j+"_bills" + bills_month + "_1.html");
        //请求有可能会返回系统繁忙信息，如果遇到该情况 判断三次
        billdetailHtml=checkCurrentNetBusy(billdetailHtml,postdatas,"https://creditcard.ecitic.com/citiccard/newonline/billQuery.do?func=queryBillInfo")
        storeDataToFile(context,billdetailHtml, j+"_bills" + bills_month + "_2.html");

        if (billdetailHtml.indexOf("代理服务器没有响应")!==-1) {
            logger.info("任务" + context.get(Constants.LUA_TASK_KEY) + "账号信息：代理服务器没有响应");
            return;
        }
        try {
            //解析已出账单详情页面
            parseBillDetailInfo(billdetailHtml, bills);
        } catch (e) {
            statCaughtException(context, e);
            e.printStackTrace();
        }
    }
}
/**
 * 正则表达式组 多个组
 *
 * @param express
 * @param content
 * @return
 */
function getMatch( express,  content) {

    var matcher = Pattern.compile(express).matcher(content);

    var arrMatch = new ArrayList();
    while (matcher.find()) {

        var temp = new ArrayList();
        for (var i = 1; i <= matcher.groupCount(); i++) {
            temp.add(matcher.group(i));
        }
        arrMatch.add(temp);
    }
    return arrMatch;
}



var luaFuncs = {
    getCookie :function () {
        var map = new HashMap();
        map.put("method","getCookie");
        return sendAndReceive(map)
    },

    zx_check_sms :function(){
        var map = new HashMap();
        map.put("method","zx_check_sms");
        return sendAndReceive(map)
    },
    zx_login: function(){
        var map = new HashMap();
        map.put("method","zx_login");
        return sendAndReceive(map)
    },
    get_html_2:function(){
        var map = new HashMap();
        map.put("method","get_html_2");
        return sendAndReceive(map)
    },
    zx_receive_message:function(verifyMessage){
        var map = new HashMap();
        map.put("method","zx_receive_message");
        map.put("smsMessage",verifyMessage);
        return sendAndReceive(map)
    } ,
    zx_check_img:function(){
        var map = new HashMap();
        map.put("method","zx_check_img");
        return sendAndReceive(map)
    },

    zx_send_img:function(code){
        var map = new HashMap();
        map.put("method","zx_send_img");
        map.put("img",code);
        return sendAndReceive(map)
    },
    zx_jumpByUrl:function(url){
        var map = new HashMap();
        map.put("method","zx_jumpByUrl");
        return sendAndReceive(map)
    },
    zx_get_html:function(){
        var map = new HashMap();
        map.put("method","zx_get_html");
        return sendAndReceive(map)
    },

    zx_get_html:function() {
        var map = new LinkedHashMap();
        map.put("method", "zx_get_html");
        return sendAndReceive(map);
    },
    /**
     * 老版-登录 使用keypress、mouseleftclick等方法点击之后输入
     * @param loginTemp
     * @param password
     * @return
     * @author lijian
     */
    zx_input_usernameAndPassword:function (loginTemp, password) {
        var map = new LinkedHashMap();
        map.put("method", "zx_input_usernameAndPassword");
        map.put("loginTemp", loginTemp);
        map.put("password", password);
        return sendAndReceive(map);
    },
    /**
     * 老版本 使用keypress输入验证码  如果为第二次输入，则需要注入js将已经输入的验证码取消掉
     * @param imgCode
     * @return
     */
    zx_input_imgCode:function (imgCode,time) {
        var map = new LinkedHashMap();
        map.put("method", "zx_input_imgCode");
        map.put("imgCode", imgCode);
        map.put("times", time);
        return  sendAndReceive(map);
    },
    /**
     * 老版本-登录之后检查登录是否成功的状态
     * @return
     */
    zx_check_loginStatus:function () {
        var map = new LinkedHashMap ();
        map.put("method", "zx_check_loginStatus");
        return  sendAndReceive(map);
    },

    /**
     * 老版本  -设置短信验证码的值，并且点击登录按钮
     * @return  短信错误-->会有弹出窗口，将弹出窗口的信息完整返回
     * 			短信正确-->lua通过url的变化来确定页面跳转成功 标志为SUCCESS
     */
    zx_input_sms_and_check :function(sms) {
        var map = new LinkedHashMap ();
        map.put("method", "zx_input_sms_and_check");
        map.put("sms", sms);
        return  sendAndReceive(map);
    },

    /**
     * 截取当前屏幕的状态
     * @return
     */
    getScreenShots :function() {
        var map=new LinkedHashMap();
        map.put("method", "getScreenShots");
        return sendAndReceive(map);
    },
    /**
     * 获取文本内容
     */
    getInnerHTML:function(id){
        var map=new LinkedHashMap();
        map.put("method", "getInnerHTML");
        map.put("id",id);
        return sendAndReceive(map);
    },

    /**
     * 清空文本内容
     */
    clearInnerHTML:function(id){
        var map=new LinkedHashMap();
        map.put("method", "clearInnerHTML");
        map.put("id",id);
        return sendAndReceive(map);
    }
}
